#include "bencode.h"
#include <stdio.h>
#include <stdlib.h>

void printNode(be_node *node){
    if(node->type==BE_STR){
        printf("%s\n", node->val.s);
    }else if(node->type==BE_INT){
        printf("%li\n", node->val.i);
    }else if(node->type==BE_LIST){
        int length, i;
        
        printf("[\n");
        
        for (i = 0; node->val.l[i]; ++i) {
            printNode(node->val.l[i]);
        }
        
        /*length = sizeof(node->val.l)/sizeof(be_node*);
        
        for(i=0; i<length; i++){
            printNode(node->val.l[i]);
        }*/
        printf("]\n");
    }else if(node->type==BE_DICT){
        int i;
        printf("{\n");
        
        for (i = 0; node->val.d[i].val; ++i) {
            printf("%s=", node->val.d[i].key);
            printNode(node->val.d[i].val);
        }
        printf("}\n");
    }

}

void handleFile(FILE *fp, int size){
    char buffer[size];
    
    fgets(buffer, size, fp);
    printNode(be_decode(buffer));    
}

void readFile(char* filename){
    FILE *fp;
    int size;
    
    fp = fopen ( filename, "r" ) ;
    
    if(fp==NULL){
        printf("File %s doesn't exists!\n", filename);
        exit(0);
    }
    
    fseek(fp, 0, SEEK_END); // seek to end of file
    size = ftell(fp)/sizeof(char); // get current file pointer
    fseek(fp, 0, SEEK_SET); // seek back to beginning of file
    printf("Size: %d chars\n", size);
    
    handleFile(fp, size);
    fclose(fp);
}

int main(int argc, char *argv[]){
    char* filename;
    
    if(argc==1){
        printf("Usage: ./as3_t2 <filename>\n");
        exit(0);
    }else{
        filename = argv[1];
        readFile(filename);
        //handleFile();
       // closeFile();
    }
    
    
    
    return 0;
}




